<template>
  <div class="layout">
    <!-- 左侧导航栏 -->
    <div class="left-nav">
      <div class="nav-title">
        <span class="nav-text">分组管理</span>
        <el-tooltip content="添加分组">
          <el-icon color="#FF6B00" @click="addGroup(false, firstId)"><plus /></el-icon>
        </el-tooltip>
      </div>
      <div class="groups block">
        <el-input class="search_group" v-model="filterText" placeholder="输入分组" />
        <el-tree
          ref="treeRef"
          class="filter-tree"
          :data="groupData"
          :props="defaultProps"
          :filter-node-method="filterNode"
          :default-expand-all="true"
        >
          <template #default="{ node, data }">
            <el-tooltip placement="right" effect="light">
              <template #content>
                <el-link
                  class="link-text"
                  :underline="false"
                  type="primary"
                  @click="addGroup(false, data)"
                  >添加子分组</el-link
                ><br />
                <el-link
                  class="link-text"
                  :underline="false"
                  type="primary"
                  @click="addGroup(true, data)"
                  >编辑</el-link
                ><br />
                <el-link
                  class="link-text"
                  :underline="false"
                  type="primary"
                  @click="removeGroup(data)"
                  >删除</el-link
                ><br />
                <!-- <el-link class="link-text" :underline="false" type="primary" v-show="data.is_local">同步至企微</el-link> -->
              </template>
              <div
                class="hover-text"
                @mouseover="mouseOver(data)"
                @mouseleave="mouseLeave(data)"
                @click="changeData(data)"
              >
                <div :class="selectId == data.id ? 'hover-detail-color' : 'hover-detail'">
                  {{ `${data.name}（${data.nums}）` }}
                </div>
                <el-icon color="#FF6B00" class="hover-icon" v-show="data.showEdit"
                  ><more-filled
                /></el-icon>
              </div>
            </el-tooltip>
          </template>
        </el-tree>
      </div>
    </div>
    <!-- 添加分组 -->
    <Dialog :appDialog="appDialog">
      <el-form
        ref="ruleFormRef"
        :model="addGroupingForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
      >
        <el-form-item label="选择分组" prop="selectGroup">
          <el-cascader
            v-model="addGroupingForm.selectGroup"
            :options="groupData"
            :props="defaultProps"
            placeholder="请选择分组"
            filterable
            @expand-change="ceateChageGroup"
          />
        </el-form-item>
        <el-form-item label="分组名称" prop="name">
          <el-input
            v-model="addGroupingForm.name"
            placeholder="请输入分组名称"
            maxlength="12"
            show-word-limit
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
    </Dialog>
    <!-- 删除弹框 -->
    <ZWDeletdialog ref="groupDialogRef" @submit="delBtn" />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, reactive, onMounted, computed } from "vue";
import { ElMessage, ElTree, ElForm } from "element-plus";
import Dialog from "@/components/Dialog.vue";
import ZWDeletdialog from "@/components/ZWDeletdialog.vue";
import { creatGroup, updateGroup, delGroup, getGroupList } from "@/api/concreation";
import { deepClone } from "@/utils/utils";
import bus from "@/utils/bus";
const ruleFormRef = ref<InstanceType<typeof ElForm>>();
const treeRef = ref<InstanceType<typeof ElTree>>();
const emit = defineEmits(["submit"]);
import { useStore } from "@/store";
const store = useStore();
const groupDialogRef = ref(null);
interface Tree {
  id: number;
  name: string;
  children?: Tree[];
}
const selectId = ref(0);
const filterText = ref(""); // 搜索分组
const showEdit = ref(false); //是否展示部门编辑
const isUpdate = ref(false); //是否是编辑弹框
const firstId = ref(4);
const pId = ref(4); //父元素ID
// 1-文本 2-图片 3-音频 4-视频 5-文件 6-链接文章 7-链接引用 8-朋友圈素材
const type = computed(() => {
  return store.getters["content/type"];
});
const getParentId = (key: number, data: any[]) => {
  let flag: boolean = false;
  data.forEach((item: any) => {
    if (item.id == key) {
      flag = true;
    } else {
      if (item.children && item.children.length > 0) {
        let res = getParentId(key, item.children);
        if (res) pId.value = item.id;
      }
    }
  });
  return flag;
};
// 取消按钮
const cancelHandel = () => {
  appDialog.visible = false;
  isUpdate.value = false;
  ruleFormRef.value.resetFields();
};
// 保存按钮
const submitHandel = () => {
  ruleFormRef.value.validate(async (valid: any) => {
    if (valid) {
      let key = isUpdate.value ? "group_id" : "pid";
      let params = {
        type: type.value,
        name: addGroupingForm.name,
        group_id: selectId.value,
        pid: addGroupingForm.selectGroup,
      };
      console.log(params, isUpdate.value, "====");
      isUpdate.value ? await updateGroup(params) : await creatGroup(params);
      ElMessage.success(`${isUpdate ? "更新" : "创建"}分组成功`);
      getGroup();
      cancelHandel();
    }
  });
};
const ceateChageGroup = (val: any) => {
  console.log(val, 2222);
};
// 弹框相关配置
const appDialog = reactive({
  visible: false,
  title: `创建分组`,
  width: "500px",
  cancel: cancelHandel,
  submit: submitHandel,
  cancelText: "取消",
  submitText: "保存",
});
// 添加分组表单
const addGroupingForm = reactive({
  selectGroup: 0, // 选择分组
  name: "", // 添加分组名称
});
// 添加分组校验规则
const rules = reactive({
  name: [
    {
      required: true,
      message: "请填写分组名称",
      trigger: "blur",
    },
  ],
});

const defaultProps = {
  checkStrictly: true,
  emitPath: false,
  label: "name",
  value: "id",
};

watch(filterText, (val) => {
  treeRef.value!.filter(val);
});
// 搜索分组
const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.name.indexOf(value) !== -1;
};
// 分组 tree
const groupData = ref([]);

//鼠标移入
const mouseOver = (data: any) => {
  selectId.value = data.id;
  data.showEdit = true;
};
//鼠标移出
const mouseLeave = (data: any) => {
  selectId.value = 0;
  data.showEdit = false;
};
//切换id
const changeData = (data: any) => {
  emit("submit", data);
  // bus.emit("getImagesList");
  selectId.value = data.id;
  store.dispatch("content/group", {
    groupId: data.id,
  });
};

// 新增/编辑分组的弹框
const addGroup = (flag: boolean, data?: any) => {
  getParentId(data.id, groupData.value);
  isUpdate.value = flag;
  appDialog.title = `${flag ? "更新" : "创建"}分组`;
  selectId.value = data.id;
  addGroupingForm.selectGroup = flag ? pId.value : data.id || data;
  addGroupingForm.name = flag ? data.name : "";
  appDialog.visible = true;
};
// 删除
const removeGroup = (data: any) => {
  selectId.value = data.id;
  groupDialogRef.value.appDialog.visible = true;
};
// 删除分组确认按钮
const delBtn = () => {
  delGroup({
    group_id: selectId.value,
  }).then((res: any) => {
    groupDialogRef.value.appDialog.visible = false;
    ElMessage.success(`删除分组成功`);
    getGroup();
  });
};
// 获取分组列表详情
const getGroup = () => {
  getGroupList({
    type: type.value,
  }).then((res: any) => {
    let defaultId = res.data[0].id;
    let result: any[] = [
      {
        name: "全部分组",
        id: "all",
        nums: 0,
        children: [],
      },
    ];
    if (res.data.length > 0) {
      result[0].nums = res.total;
      result[0].children = res.data;
    }
    store.dispatch("content/group", {
      groupList: result,
      groupId: defaultId,
    });
    firstId.value = defaultId;
    groupData.value = result;
  });
};
watch(type, () => {
  getGroup();
});
</script>

<style lang="scss" scoped>
.layout {
  display: flex;
  .left-nav {
    width: 270px;
    box-sizing: border-box;
    // height: 600px;
    border: 1px solid #eaeaea;
    background-color: #ffffff;
    padding: 16px;
    margin-right: 16px;
    box-shadow: 0px 0.5px 10px rgba(0, 0, 0, 0.2);
    .nav-title {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
    }
    .nav-text {
      font-size: 16px;
      font-weight: 600;
      color: #33302d;
    }
    .nav-input {
      width: 238px;
      padding: 16px 0 20px 0;
    }
    .el-tree-node__content {
      height: 35px !important;
    }
    .hover-text {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .hover-detail {
        color: #535456;
        font-size: 14px;
      }
      .hover-detail-color {
        color: #ff6b00;
      }
      .hover-detail:hover {
        color: #ff6b00;
      }
      .hover-icon {
        transform: rotate(90deg);
      }
    }
    .search-list {
      display: flex;
      flex-direction: column;
      .search-detail {
        margin: 0;
        color: #33302d;
      }
      .search-detail:hover {
        background-color: #f5f7fa;
      }
      .hover-text {
        line-height: 35px;
      }
    }
    .no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .nodata-img {
        margin: 30px 0 30px 15px;
        width: 150px;
        height: 120px;
      }
    }
    .groups {
      color: #33302d;
      font-size: 14px;
      .search_group {
        margin: 20px 0;
      }
      :deep .el-tree-node__expand-icon {
        color: #ff6b00;
      }
      :deep .el-tree-node__content:hover {
        background: #fffaf9;
      }
      :deep .el-tree {
        --el-tree-node-hover-bg-color: #fffaf9;
      }
    }
    :deep.el-popper {
      text-align: center !important;
    }
  }
}
</style>
